package com.magicborrow.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;
import android.util.Log;

import com.magicborrow.beans.AddressBean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;


public class AddressHostUtils {
	public static ArrayList<AddressBean> getLocalHost(Context context) {
		ArrayList<AddressBean> localHost = null;
		SharedPreferences preferences = context.getSharedPreferences("base64", Activity.MODE_PRIVATE);
		String productBase64 = preferences.getString("Address", "utf-8");

		//读取字节
		byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);
		if (base64.length <= 10) {
			return null;
		}

		//封装到字节流
		ByteArrayInputStream bais = new ByteArrayInputStream(base64);
		try {
			//再次封装
			ObjectInputStream bis = new ObjectInputStream(bais);
			try {
				//读取对象
				localHost = (ArrayList<AddressBean>) bis.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (StreamCorruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return localHost;
	}


	public static void saveLocalHost(Context context, ArrayList<AddressBean> localHosts) {
		SharedPreferences preferences = context.getSharedPreferences("base64",
				Activity.MODE_PRIVATE);
		// 创建字节输出流

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			// 创建对象输出流，并封装字节流
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			// 将对象写入字节流
			oos.writeObject(localHosts);
			// 将字节流编码成base64的字符窜
			String oAuth_Base64 = new String(Base64.encode(baos
					.toByteArray(), Base64.DEFAULT));
			Editor editor = preferences.edit();
			editor.putString("Address", oAuth_Base64);

			editor.commit();
		} catch (IOException e) {
			// TODO Auto-generated
		}
		Log.i("ok", "存储成功");

	}
	 public static void cleanLocalhost(Context context){
		 saveLocalHost(context, null);

	 }


}
